<template>
  <van-dropdown-menu class="search-dropdown">
    <van-dropdown-item
      ref="menu"
      v-model="val"
      :options="options"
      @open="open"
      @opened="opened"
      @close="close"
      @change="change"
    />
  </van-dropdown-menu>
</template>

<script>
import { debounce } from '@utils/index'
import { getOverflowAutoEl } from '@utils/style'

export default {
  props: {
    value: {
      type: String,
      default: ''
    },
    getOptions: {
      type: Function,
      default() {
        return () => Promise.resolve()
      }
    },
    immediate: {
      type: [Boolean],
      default: false
    }
  },
  data() {
    return {
      getData: debounce(() => {
        this.getOptions().then(res => {
          this.options = res || []; //{text:'京A12345'+i,value:'京A12345'+i}
        });
        this.$nextTick(() => {
          this.$refs.menu.toggle(true);
        });
      }, 600),
      val: '',
      options: [],/*  Array.from(Array(10),(empty,i)=>{
          return {text:'京A12345'+i,value:'京A12345'+i}
        }), */
    };
  },
  watch: {
    value(v, old) {



      v && v !== old && this.val !== v && (() => {

        this.$refs.menu.toggle(false);
        this.immediate && this.getData();
      })();
    }
  },
  mounted() {

  },
  methods: {
    getOptionsFn() {
      return this.options
    },
    setOverflow(value) {
      this.$_autoEl = this.$_autoEl || getOverflowAutoEl(this.$refs.menu.$el)
      this.$_autoEl.style.overflow = value
    },
    close() {
      this.setOverflow('auto')
      const scrollBox = this.$refs.menu.$el.querySelector('.van-popup')
      if (scrollBox) {
        scrollBox.scrollTop = 0;
      }
      this.$emit('close')
    },
    opened() {

    },
    open() {
      this.setOverflow('hidden')
      this.$nextTick(() => {
        this.val = this.value;
      })
    },
    change(v) {
      this.val = v;
      const item = this.options.find(opt => opt.value === v)
      this.$emit('input', v)
      this.$emit('change', item)
    }
  }
};
</script>

<style lang="less" scoped>
.search-dropdown {
  & /deep/ .van-cell{
    background-color: @bg-table-gray;
    &::after{
      left:0;
      right:0;
    }
  }
  & /deep/ .van-dropdown-menu__bar {
    width: 1px;
    height: 1px;
    margin-top:-1px;
    overflow: hidden;
  }
}
</style>